package com.mayflygeek.mayflyask.framework.webmvc.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mayflygeek.mayflyask.framework.webmvc.Application;
import com.mayflygeek.mayflyask.framework.webmvc.BootTask;

public class SpringWebApplicationFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void destroy() {
		Application.cleanContexts();

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		final HttpServletRequest request = (HttpServletRequest) servletRequest;
		final HttpServletResponse response = (HttpServletResponse) servletResponse;

		try {
			beforeFilter(request, response);

			filterChain.doFilter(request, response);
		} catch (ServletException e) {
			throw e;
		} finally {
			afterFilter(request, response);
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		bootstrap(filterConfig);
		sessionFactory(filterConfig);
		logger.info("====================");
		logger.info("                    ");
		logger.info("webapp init success!");
		logger.info("                    ");
		logger.info("====================");
	}

	protected void bootstrap(FilterConfig filterConfig) {
		final Map<String, BootTask> bootTasks = Application.getApplicationContext().getBeansOfType(BootTask.class);
		for (Map.Entry<String, BootTask> entry : bootTasks.entrySet()) {
			final BootTask bootTask = entry.getValue();
			bootTask.run();
		}
	}

	protected void sessionFactory(FilterConfig filterConfig) {
		final Map<String, SessionFactory> sessionFactory = Application.getApplicationContext()
				.getBeansOfType(SessionFactory.class);
		for (Map.Entry<String, SessionFactory> entry : sessionFactory.entrySet()) {
			System.out.println(entry);
		}
	}

	protected void beforeFilter(HttpServletRequest request, HttpServletResponse response) {
		Application.setRequestAndResponse(request, response);
		injectContextParams(request);
	}

	protected void afterFilter(HttpServletRequest request, HttpServletResponse response) {
		// no thing
	}

	private void injectContextParams(HttpServletRequest request) {
		RequestContexts.makeRequestContext(request);
	}

}
